﻿using CommonBase;
using CommonClass;
using DeviceMgtModule.Models;
using EnvControlLib;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Regions;
using SurveillancePro.Base.DataEnum;
using SurveillancePro.Base.Manager;
using SurveillancePro.Base.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace DeviceMgtModule.ViewModels
{
    /// <summary>
    /// 设备管理
    /// </summary>
    public class ViewModel_DeviceManagement : WorkspaceViewModel
    {
        #region Private Fields

        private WorkStateEnum _workState;
        private DeviceModel _selectedDevice, _workingDevice;
        private DelegateCommand _cmdNew, _cmdDelete, _cmdEdit, _cmdSearchList, _cmdLoadList;
        private DelegateCommand _cmdApplyUpdateOrCreate, _cmdCancelUpdateOrCreate;

        #endregion

        #region Constructor

        /// <summary>
        /// 
        /// </summary>
        /// <param name="regionManager"></param>
        public ViewModel_DeviceManagement(IRegionManager regionManager)
        {
            if (regionManager == null)
                return;

            _changeIndicatorState(true); // 默认：忙

            base.BaseRegionManager = regionManager;
            base.ViewName = SurveillancePro.Base.Common.ViewNames.DeviceMgtModule_DeviceManagement;
            base.HeaderTitle = "设备管理";
            base.HeaderImageSource = string.Format(ConstantString.IMAGE_URL, "Question");
            base.IsShowCloseButton = Visibility.Visible;

            _initializeList(string.Empty); // 加载全部
        }

        #endregion

        #region Base Class Overrides

        protected override void OnDispose()
        {
            _dispose();
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// 设备列表
        /// </summary>
        public ObservableCollection<DeviceModel> DeviceList { get; private set; }

        /// <summary>
        /// 创建、编辑 Device
        /// </summary>
        public DeviceModel WorkingDevice
        {
            get { return _workingDevice; }
            set
            {
                if (value == _workingDevice) return;
                _workingDevice = value;
                base.OnPropertyChanged("WorkingDevice");
            }
        }

        /// <summary>
        /// 列表所选 Device
        /// </summary>
        public DeviceModel SelectedDevice
        {
            get { return _selectedDevice; }
            set
            {
                if (value == _selectedDevice) return;
                _selectedDevice = value;
                base.OnPropertyChanged("SelectedDevice");
            }
        }

        /// <summary>
        /// 状态
        /// </summary>
        public WorkStateEnum WorkingState
        {
            get { return _workState; }
            set
            {
                if (value == _workState) return;
                _workState = value;

                base.OnPropertyChanged("WorkingState");
                SurveillancePro.Base.Reflector.WorkingStateProperty.OnWorkingStatePropertyChanged(this); // 更新界面
            }
        }

        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_New
        {
            get
            {
                if (_cmdNew == null)
                {
                    _cmdNew = new DelegateCommand(_createItem, _canCreateItem);
                }
                return _cmdNew;
            }
        }

        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_SearchList
        {
            get
            {
                if (_cmdSearchList == null)
                {
                    _cmdSearchList = new DelegateCommand(_searchItemList, _canSearchItemList);
                }
                return _cmdSearchList;
            }
        }

        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_LoadList
        {
            get
            {
                if (_cmdLoadList == null)
                {
                    _cmdLoadList = new DelegateCommand(_loadItemList, _canLoadItemList);
                }
                return _cmdLoadList;
            }
        }

        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_Edit
        {
            get
            {
                if (_cmdEdit == null)
                {
                    _cmdEdit = new DelegateCommand(_editItem, _canEditItem);
                }
                return _cmdEdit;
            }
        }

        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_ApplyUpdateOrCreate
        {
            get
            {
                if (_cmdApplyUpdateOrCreate == null)
                {
                    _cmdApplyUpdateOrCreate = new DelegateCommand(_applyUpdateOrCreateItem, _canApplyUpdateOrCreateItem);
                }
                return _cmdApplyUpdateOrCreate;
            }
        }

        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_CancelUpdateOrCreate
        {
            get
            {
                if (_cmdCancelUpdateOrCreate == null)
                {
                    _cmdCancelUpdateOrCreate = new DelegateCommand(_cancelUpdateOrCreateItem, _canCancelUpdateOrCreateItem);
                }
                return _cmdCancelUpdateOrCreate;
            }
        }

        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_Delete
        {
            get
            {
                if (_cmdDelete == null)
                {
                    _cmdDelete = new DelegateCommand(_deleteItem, _canDeleteItem);
                }
                return _cmdDelete;
            }
        }

        /// <summary>
        /// 列表选择时
        /// </summary>
        public ICommand Cmd_DataGridSelect
        {
            get
            {
                return new DelegateCommand(() =>
                {
                    ViewModel_DeviceManagement vm = (ViewModel_DeviceManagement)this;

                    //When another tab item is selected, data context of this tab item 
                    //becomes null, also this event will be raised, therefore we need to 
                    //add "if" to protect againt exception.
                    if (vm != null)
                        vm._selectItem();
                });
            }
        }

        /// <summary>
        /// 查询设备名称 条件值
        /// </summary>
        public string Txt_SearchDeviceText { get; set; }

        /// <summary>
        /// 是否显示 进度条
        /// </summary>
        public bool Indicator_IsBusy { get; set; }

        #endregion

        #region Public Events

        /// <summary>
        /// 用于全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            (sender as TextBox).SelectAll(); // 全选
        }

        #endregion

        #region Event Handling Methods

        void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null && e.NewItems.Count != 0)
                foreach (DeviceModel device in e.NewItems)
                    device.PropertyChanged += this.OnDeviceModelPopertyChanged;

            if (e.OldItems != null && e.OldItems.Count != 0)
                foreach (DeviceModel device in e.OldItems)
                    device.PropertyChanged -= this.OnDeviceModelPopertyChanged;
        }

        void OnDeviceModelPopertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // Blank for now
        }

        #endregion

        #region Private Methods

        #region DelegateCommand

        private bool _canSearchItemList()
        {
            return (WorkingState != WorkStateEnum.Editing && WorkingState != WorkStateEnum.Creating);
        }

        private void _searchItemList()
        {
            if (DeviceList != null) _dispose();

            _initializeList(Txt_SearchDeviceText); // 条件查询
        }

        private bool _canLoadItemList()
        {
            return (WorkingState != WorkStateEnum.Editing && WorkingState != WorkStateEnum.Creating);
        }

        private void _loadItemList()
        {
            if (DeviceList != null) _dispose();

            _initializeList(string.Empty); // 加载全部
        }

        private bool _canSelectItem()
        {
            return (WorkingState != WorkStateEnum.Editing && WorkingState != WorkStateEnum.Creating);
        }

        private void _selectItem()
        {
            if (SelectedDevice == null || DeviceList.Count == 0) return;
            if (WorkingDevice == null) WorkingDevice = new DeviceModel();

            Utilities.CopyObject(SelectedDevice, WorkingDevice); // 复制引用
            WorkingState = WorkStateEnum.ItemSelected;            
        }

        private bool _canCreateItem()
        {
            return (WorkingState != WorkStateEnum.Editing && WorkingState != WorkStateEnum.Creating);
        }

        private void _createItem()
        {
            SelectedDevice = null;
            WorkingDevice = new DeviceModel();
            WorkingState = WorkStateEnum.Creating;

            WorkingDevice.DeviceList = DeviceList; // 传列表
        }

        private bool _canEditItem()
        {
            return (WorkingState == WorkStateEnum.ItemSelected);
        }

        private void _editItem()
        {
            WorkingState = WorkStateEnum.Editing;

            WorkingDevice.DeviceList = DeviceList; // 传列表
            WorkingDevice.OrigDriverText = WorkingDevice.DriverText; // 暂存 DriverText
            WorkingDevice.OrigDriverIP = WorkingDevice.DriverIP; // 暂存 DriverIP
            WorkingDevice.OrigDriverPort = WorkingDevice.DriverPort; // 暂存 DriverPort
        }

        private bool _canApplyUpdateOrCreateItem()
        {
            return (WorkingState == WorkStateEnum.Editing || WorkingState == WorkStateEnum.Creating);
        }

        /// <summary>
        /// 新建 | 修改
        /// </summary>
        private void _applyUpdateOrCreateItem()
        {
            if (WorkingState == WorkStateEnum.Editing) // 修改时
            {
                try
                {
                    _changeIndicatorState(true);

                    if (WorkingDevice.IsValid != 0) // 存在错误
                    {
                        AutoCloseNoticeWindow.Show(WorkingDevice.ErrorInfo, true);
                        //AutoCloseNoticeWindow.Show(string.Format("系统中发现{0}个错误，请检查页面！", WorkingDevice.IsValid), true);
                        _changeIndicatorState(false);
                        return;
                    }
                    else
                    {
                        int resultCount = WorkingDevice.SaveModified();
                        if (resultCount > 0)
                        {
                            MessageBox.Show("数据修改成功！", ConstantString.MSG_COMPANY);

                            WorkingState = WorkStateEnum.ItemSelected;
                            WorkingDevice.DriverPwd = WorkingDevice.DriverConfirmPwd = string.Empty; // 清空密码
                            Utilities.CopyObject(WorkingDevice, SelectedDevice); // 更新数据
                            EventManagers.RefreshTree();
                        }
                        else
                            MessageBox.Show("数据修改失败！", ConstantString.MSG_COMPANY);
                    }
                }
                catch (Exception e)
                {
                    ShowError(e.ToString(), "错误：更新设备");
#if DEBUG
                    Debug.WriteLine(e.Message);
#endif
                }
            }
            else if (WorkingState == WorkStateEnum.Creating) // 新建时
            {
                try
                {
                    _changeIndicatorState(true);

                    if (WorkingDevice.IsValid != 0) // 存在错误
                    {
                        AutoCloseNoticeWindow.Show(WorkingDevice.ErrorInfo, true);
                        //AutoCloseNoticeWindow.Show(string.Format("系统中发现{0}个错误，请检查页面！", WorkingDevice.IsValid), true);
                        _changeIndicatorState(false);
                        return;
                    }
                    else
                    {
                        int resultCount = WorkingDevice.SaveNew();
                        if (resultCount > 0)
                        {
                            MessageBox.Show("数据新增成功！", ConstantString.MSG_COMPANY);

                            WorkingState = WorkStateEnum.NoItemSelected;
                            _initializeList(string.Empty); // 重新加载表格
                            EventManagers.RefreshTree();
                        }
                        else
                            MessageBox.Show("数据新增失败！", ConstantString.MSG_COMPANY);
                    }
                }
                catch (Exception e)
                {
                    ShowError(e.ToString(), "错误：创建设备");
#if DEBUG
                    Debug.WriteLine(e.Message);
#endif
                }
            }

            _changeIndicatorState(false);
        }

        private bool _canCancelUpdateOrCreateItem()
        {
            return (WorkingState == WorkStateEnum.Editing || WorkingState == WorkStateEnum.Creating);
        }

        private void _cancelUpdateOrCreateItem()
        {
            if (WorkingState == WorkStateEnum.Editing)
            {
                Utilities.CopyObject(SelectedDevice, WorkingDevice); // 更新数据
                WorkingState = WorkStateEnum.ItemSelected;
            }
            else if (WorkingState == WorkStateEnum.Creating)
            {
                WorkingDevice = null;
                WorkingState = WorkStateEnum.NoItemSelected;
            }
        }

        private bool _canDeleteItem()
        {
            return (WorkingState == WorkStateEnum.ItemSelected);
        }

        /// <summary>
        /// 删除
        /// </summary>
        private void _deleteItem()
        {
            ConfirmWindow cw = new ConfirmWindow("你想删除这个项目吗？");
            cw.Closed += new EventHandler(_cw_Closed);
            cw.ShowDialog();
        }

        private void _cw_Closed(object sender, EventArgs e)
        {
            if ((sender as ConfirmWindow).DialogResult != true)
                return;

            try
            {
                _changeIndicatorState(true);
                int resultCount = WorkingDevice.DeleteRec(WorkingDevice.ID);
                if (resultCount > 0)
                {
                    MessageBox.Show("数据删除成功！", ConstantString.MSG_COMPANY);

                    SelectedDevice = null;
                    WorkingDevice = null;
                    WorkingState = WorkStateEnum.NoItemSelected;
                    _initializeList(string.Empty); // 加载全部
                    EventManagers.RefreshTree();
                }
                else
                    MessageBox.Show("数据删除失败！", ConstantString.MSG_COMPANY);
            }
            catch (Exception ex)
            {
                ShowError(ex.ToString(), "错误：删除设备");
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }

            _changeIndicatorState(false);
        }

        #endregion

        /// <summary>
        /// 修改 进度条 状态
        /// </summary>
        /// <param name="state"></param>
        private void _changeIndicatorState(bool state)
        {
            Indicator_IsBusy = state;
            base.OnPropertyChanged("Indicator_IsBusy");
        }

        /// <summary>
        /// 更新界面
        /// </summary>
        /// <param name="model"></param>
        private void _updateLayout(DeviceModel model)
        {
            SelectedDevice = model;
            base.OnPropertyChanged("DeviceList");

            if (SelectedDevice == null)
            {
                WorkingDevice = null;
                WorkingState = WorkStateEnum.NoItemSelected;
            }
            else
            {
                WorkingDevice = new DeviceModel();
                Utilities.CopyObject(SelectedDevice, WorkingDevice); // 复制引用
                WorkingState = WorkStateEnum.ItemSelected;
            }
        }

        /// <summary>
        /// 加载列表，并返回第一行，用于默认选中
        /// </summary>
        /// <param name="devices"></param>
        /// <returns></returns>
        private DeviceModel _loadDeviceList(DeviceModel[] devices)
        {
            if (devices == null)
            {
                _changeIndicatorState(false);
                return null;
            }

            DeviceList = new ObservableCollection<DeviceModel>();
            _changeIndicatorState(true);

            foreach (DeviceModel device in devices)
            {
                device.PropertyChanged += this.OnDeviceModelPopertyChanged;
                DeviceList.Add(device);
            }
            DeviceList.CollectionChanged += this.OnCollectionChanged;

            _changeIndicatorState(false);
            return devices.FirstOrDefault();
        }

        /// <summary>
        /// 初始化列表，可以：
        /// <para>1. 获取所有列表 -- string.Empty | "" | null</para>
        /// <para>2. 条件查询列表</para>
        /// </summary>
        /// <param name="txtDeviceID">查询 机构ID</param>
        private void _initializeList(string txtDeviceID)
        {
            _changeIndicatorState(true);
            
            try
            {
                DeviceList = new ObservableCollection<DeviceModel>();

                if (string.IsNullOrWhiteSpace(txtDeviceID)) // 查询全部
                {
                    DataRowCollection rows = DeviceModel.Load_All();
                    DeviceModel[] devices = _loadAll(rows);
                    _updateLayout(_loadDeviceList(devices)); // 加载全部，并更新界面
                }
                //else // 条件查询
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }

            _changeIndicatorState(false);
        }

        /// <summary>
        /// 获取所有 Device Model -- 绑定 Model 中的方法与属性
        /// </summary>
        /// <param name="deviceList"></param>
        /// <returns></returns>
        private DeviceModel[] _loadAll(DataRowCollection deviceList)
        {
            if (deviceList == null || deviceList.Count <= 0)
            {
                _changeIndicatorState(false);
                return null;
            }

            DeviceModel[] _devices = new DeviceModel[deviceList.Count];
            for (int i = 0; i < deviceList.Count; i++)
                _devices[i] = new DeviceModel(deviceList[i]);

            return _devices;
        }

        /// <summary>
        /// 获取指定 Device Model -- 绑定 Model 中的方法与属性
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private DeviceModel _loadOne(DataRow device)
        {
            return new DeviceModel(device);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        private void _dispose()
        {
            if (DeviceList != null)
            {
                foreach (DeviceModel device in DeviceList)
                    device.Dispose();

                DeviceList.Clear();
                DeviceList.CollectionChanged -= this.OnCollectionChanged;
            }
        }

        #endregion
    }
}
